<template>
  <el-dialog
    v-model="dialogVisible"
    title="打印机服务管理"
    width="650px"
    :destroy-on-close="true"
    :close-on-click-modal="false">
    <div class="printer-selector-container">
      <el-form label-width="100px">
        <!-- 打印服务开关 -->
        <el-form-item label="打印服务:">
          <div class="service-switch-container">
            <el-switch
              v-model="printServiceEnabled"
              active-text="启用"
              inactive-text="禁用"
              @change="togglePrintService"
            />
            <el-tag 
              v-if="printServiceEnabled" 
              :type="isElectronAvailable ? 'success' : 'danger'"
              effect="dark"
              size="small"
              class="connection-status-tag"
            >
              {{ isElectronAvailable ? '已连接' : '未连接' }}
            </el-tag>
          </div>
        </el-form-item>
        
        <!-- 连接失败警告 -->
        <el-form-item v-if="printServiceEnabled && !isElectronAvailable && !connectionError" label="">
          <el-alert
            type="warning"
            show-icon
            :closable="false"
            title="打印服务未连接"
            description="打印服务未连接或无法访问，请检查打印服务是否已启动"
          />
        </el-form-item>
        
        <!-- 连接错误提示 -->
        <el-form-item v-if="printServiceEnabled && connectionError" label="">
          <el-alert
            type="error"
            show-icon
            :closable="false"
            :title="connectionError"
          />
        </el-form-item>
        
        <!-- 连接设置 -->
        <el-form-item v-if="printServiceEnabled" label="连接设置:">
          <div class="connection-settings">
            <el-input v-model="portSettings.host" placeholder="主机地址" class="host-input">
              <template #prepend>主机</template>
            </el-input>
            <el-input-number v-model="portSettings.port" :min="1" :max="65535" placeholder="端口号" class="port-input" controls-position="right" />
            <el-button type="primary" @click="connectToCustomPort" :loading="connecting">
              {{ isElectronAvailable ? '重新连接' : '连接' }}
            </el-button>
          </div>
        </el-form-item>
        
        <!-- 快速输入 IP:端口 -->
        <el-form-item v-if="printServiceEnabled" label="快速输入:">
          <div class="connection-settings">
            <el-input 
              v-model="quickAddressInput" 
              placeholder="请输入格式如 192.168.1.47:20000" 
              class="quick-input"
              @input="handleQuickInputChange"
              clearable
            >
              <template #prepend>IP:端口</template>
            </el-input>
            <el-tooltip content="格式：IP地址:端口号，例如 192.168.1.47:20000  |  127.0.0.1:20000  |  localhost:20000" placement="top">
              <el-icon class="info-icon"><InfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </el-form-item>
        
        <!-- 连接成功提示 -->
        <el-form-item v-if="printServiceEnabled && isElectronAvailable" label="">
          <el-alert
            type="success"
            show-icon
            :closable="false"
            title="打印服务已连接"
            description="已成功连接到打印服务，可以选择默认打印机"
          />
        </el-form-item>
        
        <!-- 打印机选择 -->
        <el-form-item label="选择打印机:">
          <div class="printer-select-container">
            <el-select 
              v-model="selectedPrinter" 
              placeholder="请选择打印机" 
              filterable 
              class="printer-select"
            >
              <el-option
                v-for="printer in printerList"
                :key="printer.name"
                :label="printer.name"
                :value="printer.name"
              />
            </el-select>
            <el-button 
              type="success" 
              plain 
              icon="RefreshRight" 
              @click="refreshPrinterList" 
              :loading="refreshingPrinters"
              title="刷新打印机列表"
            ></el-button>
          </div>
        </el-form-item>
        
        <!-- 默认打印机显示 -->
        <el-form-item v-if="selectedPrinter" label="当前默认:">
          <el-tag type="success">{{ selectedPrinter }}</el-tag>
        </el-form-item>
        
        <!-- 无打印机提示 -->
        <el-form-item v-if="!printerList.length">
          <el-alert
            type="info"
            show-icon
            :closable="false"
            title="未检测到可用打印机"
            description="请确保您的电脑已连接打印机并已正确安装驱动"
          />
        </el-form-item>

        <!-- 显示当前按钮的标识 -->
        <el-form-item v-if="buttonKey" label="配置来源:">
          <el-tag type="info">{{ buttonKey }}</el-tag>
        </el-form-item>
      </el-form>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="setDefaultPrinter" :disabled="!selectedPrinter">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { InfoFilled, RefreshRight } from '@element-plus/icons-vue';
import PrintService from '@/print-sdk/print-service';

// 定义props和emits
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  // 添加buttonKey属性，用于标识不同的按钮
  buttonKey: {
    type: String,
    default: 'default'
  }
});

const emit = defineEmits(['update:visible', 'printer-change']);

// 弹窗显示状态
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
});

// 关闭弹窗
const closeDialog = () => {
  dialogVisible.value = false;
};

// PrintService相关状态
const printServiceEnabled = ref(false);
const isElectronAvailable = ref(false);
const connectionError = ref('');
const portSettings = ref({ host: 'localhost', port: 20000 });
const connecting = ref(false);
const refreshingPrinters = ref(false);
// 添加初始化标记，避免重复初始化
const isInitialized = ref(false);

// 打印机相关
const printerList = ref([]);
const selectedPrinter = ref('');

// 快速输入IP:端口
const quickAddressInput = ref('');

// 处理快速输入变化
const handleQuickInputChange = (value) => {
  if (!value) return;
  
  // 判断是否符合IP:端口格式
  const regex = /^(.+):(\d+)$/;
  const match = value.match(regex);
  
  if (match && match.length === 3) {
    // 拆分IP和端口
    const [_, host, port] = match;
    
    // 更新连接设置
    portSettings.value.host = host;
    portSettings.value.port = parseInt(port, 10);
    
    console.log(`快速输入解析 - 主机: ${host}, 端口: ${port}`);
  }
};

// 切换打印服务状态
const togglePrintService = async (value) => {
  // 存储用户选择到本地存储
  localStorage.setItem('printServiceEnabled', value ? 'true' : 'false');
  
  // 保存按钮特定的设置
  savePrinterConfigForButton({
    enabled: value
  });
  
  if (value) {
    // 启用PrintService
    try {
      // 初始化PrintService并加载打印机列表
      initPrintService()
      // 注册到全局变量
    } catch (error) {
      console.error('初始化PrintService失败:', error);
      connectionError.value = '初始化PrintService失败: ' + (error.message || '未知错误');
    }
  } else {
    // 禁用PrintService
    try {
      // 先断开PrintService连接
      if (PrintService) {
        // 注意：不要调用disconnect()，因为可能其他组件还在使用
        // 只重置当前组件的状态
        isElectronAvailable.value = false;
        connectionError.value = '';
        isInitialized.value = false;
        PrintService.disconnect();

      }
      // 重置状态
      isElectronAvailable.value = false;
      connectionError.value = '';
    } catch (error) {
      console.error('断开打印服务失败:', error);
    }
  }
};

// 初始化PrintService
const initPrintService = async () => {
  try {
    // 如果已经初始化，则不重复初始化
    if (isInitialized.value && isElectronAvailable.value) {
      console.log('PrintService已经初始化，跳过重复初始化');
      return isElectronAvailable.value;
    }

    connecting.value = true;
    connectionError.value = '';
    
    // 初始化PrintService
    await PrintService.init();
    // 只在第一次初始化时设置事件监听器
    if (!isInitialized.value) {
      PrintService.setupEventListeners();
      isInitialized.value = true;
    }
    
    // 更新状态
    isElectronAvailable.value = PrintService.isServiceAvailable();
    
   
    await connectToCustomPort();

    
    return isElectronAvailable.value;
  } catch (error) {
    console.error('初始化PrintService失败:', error);
    connectionError.value = '初始化PrintService失败: ' + (error.message || '未知错误');
    return false;
  } finally {
    connecting.value = false;
  }
};

// 从PrintService加载打印机列表
const loadPrintersFromService = async () => {
  try {
    refreshingPrinters.value = true;
    const printers = await PrintService.getPrinters();
    printerList.value = printers;
    
    // 先获取当前按钮配置中的默认打印机
    const buttonConfig = getPrinterConfigForButton();
    if (buttonConfig && buttonConfig.defaultPrinter) {
      // 检查该打印机是否存在于当前列表中
      const printerExists = printers.some(p => p.name === buttonConfig.defaultPrinter);
      if (printerExists) {
        selectedPrinter.value = buttonConfig.defaultPrinter;
      } else {
        // 如果该打印机不存在，使用全局默认打印机
        const defaultPrinter = PrintService.defaultPrinter;
        if (defaultPrinter) {
          selectedPrinter.value = defaultPrinter;
        } else if (printers.length > 0) {
          selectedPrinter.value = printers[0].name;
        }
      }
    } else {
      // 使用全局默认打印机
      const defaultPrinter = PrintService.defaultPrinter;
      if (defaultPrinter) {
        selectedPrinter.value = defaultPrinter;
      } else if (printers.length > 0) {
        selectedPrinter.value = printers[0].name;
      }
    }
    
    console.log('获取打印机列表:', printers);
    
    return printers;
  } catch (error) {
    console.error('获取打印机列表失败:', error);
    connectionError.value = '获取打印机列表失败: ' + (error.message || '未知错误');
    return [];
  } finally {
    refreshingPrinters.value = false;
  }
};

// 刷新打印机列表
const refreshPrinterList = async () => {
  if (printServiceEnabled.value && isElectronAvailable.value) {
    await loadPrintersFromService();
  } else {
    await fetchPrinters();
  }
};

// 连接到自定义端口
const connectToCustomPort = async () => {
  connecting.value = true;
  connectionError.value = '';
  
  try {
    // 使用保存的设置或默认设置
    const port = portSettings.value.port || 20000;
    const host = portSettings.value.host || 'localhost';
    
    // 直接调用PrintService的setCustomPort方法
    // 不再重新初始化PrintService和setupEventListeners
    // 这些已在PrintService内部控制避免重复
    const success = await PrintService.setCustomPort(port, host);
    
    if (success) {
      // 成功连接后不再显示成功消息，由PrintService的事件处理器统一处理
      isElectronAvailable.value = true;
      isInitialized.value = true;
      
      // 保存成功的连接设置
      localStorage.setItem('printServiceHost', host);
      localStorage.setItem('printServicePort', port.toString());
      
      // 保存按钮特定的设置
      savePrinterConfigForButton({
        host,
        port
      });
     await registerGlobalPrintService();

     await loadPrintersFromService();
    } else {
      connectionError.value = '连接失败，请检查主机和端口是否正确';
      isElectronAvailable.value = false;
    }
  } catch (error) {
    console.error('连接到自定义端口失败:', error);
    connectionError.value = '连接失败: ' + (error.message || '未知错误');
    isElectronAvailable.value = false;
  } finally {
    connecting.value = false;
  }
};

// 注册PrintService为全局变量
const registerGlobalPrintService = async () => {
  if (printServiceEnabled.value) {
    // 将PrintService注册为全局变量
    window.PrintService = PrintService;
    console.log('PrintService已注册为全局变量');
  }
};

// 获取系统打印机列表
const fetchPrinters = async () => {
  try {
    refreshingPrinters.value = true;
    
    // 如果PrintService已启用，则使用PrintService加载打印机
    if (printServiceEnabled.value && isElectronAvailable.value) {
      return await loadPrintersFromService();
    }
    
    // 否则使用系统默认打印机列表
    printerList.value = [
      { name: 'HP LaserJet Pro MFP M126nw' },
      { name: 'Canon PIXMA TS8320' },
      { name: 'Epson WorkForce WF-7720' },
      { name: 'Brother HL-L2350DW' }
    ];
    
    // 获取按钮特定的默认打印机
    const buttonConfig = getPrinterConfigForButton();
    if (buttonConfig && buttonConfig.defaultPrinter) {
      selectedPrinter.value = buttonConfig.defaultPrinter;
    } else {
      // 获取全局默认打印机
      const defaultPrinter = localStorage.getItem('defaultPrinter');
      if (defaultPrinter) {
        selectedPrinter.value = defaultPrinter;
      } else if (printerList.value.length > 0) {
        selectedPrinter.value = printerList.value[0].name;
      }
    }
  } finally {
    refreshingPrinters.value = false;
  }
};

// 设置默认打印机
const setDefaultPrinter = () => {
  if (!selectedPrinter.value) {
    ElMessage.warning('请选择一个打印机');
    return;
  }
  
  // 保存默认打印机设置
  localStorage.setItem('defaultPrinter', selectedPrinter.value);
  
  // 保存按钮特定的默认打印机设置
  savePrinterConfigForButton({
    defaultPrinter: selectedPrinter.value
  });
  
  // 如果PrintService已启用，也设置PrintService的默认打印机
  if (printServiceEnabled.value) {
    PrintService.saveDefaultPrinter(selectedPrinter.value);
  }
  
  // 广播事件，通知其他页面打印机设置已更改
  const printerChangeEvent = new CustomEvent('printerChange', {
    detail: {
      printer: selectedPrinter.value,
      buttonKey: props.buttonKey
    }
  });
  window.dispatchEvent(printerChangeEvent);
  
  // 触发打印机变更事件
  emit('printer-change', selectedPrinter.value, props.buttonKey);
  
  // 关闭弹窗
  dialogVisible.value = false;
};

// 监听buttonKey变化，当buttonKey变化时重新加载配置
watch(() => props.buttonKey, (newKey) => {
  if (dialogVisible.value) {
    // // 先加载按钮特定配置
    // loadButtonSpecificSettings();
    
    // // 只有在打印服务已启用的情况下才尝试连接
    // if (printServiceEnabled.value) {
    //   // 防抖处理，避免频繁连接
    //   const savedPort = portSettings.value.port;
    //   const savedHost = portSettings.value.host;
      
    //   // 延迟执行，给加载配置留出时间
    //   setTimeout(() => {
    //     // 确保配置已加载且组件还在显示
    //     if (dialogVisible.value && printServiceEnabled.value) {
    //       // 只有当端口或主机变化时才重新连接
    //       if (savedPort !== portSettings.value.port || savedHost !== portSettings.value.host) {
    //         connectToCustomPort();
    //       }
    //     }
    //   }, 300);
    // }
    // loadSettings();
  loadButtonSpecificSettings();
  connectToCustomPort();
  }
});

// 监听对话框可见性变化
watch(() => dialogVisible.value, (newValue) => {
  if (newValue) {
    // 对话框打开时，初始化数据
    // loadSettings();
  }
});

// 获取缓存中按钮特定的打印机配置
const getPrinterConfigForButton = () => {
  if (!props.buttonKey) return null;
  
  try {
    const configKey = `printer_config_${props.buttonKey}`;
    const configStr = localStorage.getItem(configKey);
    if (configStr) {
      return JSON.parse(configStr);
    }
  } catch (error) {
    console.error('获取按钮打印机配置失败:', error);
  }
  
  return null;
};

// 保存按钮特定的打印机配置
const savePrinterConfigForButton = (configUpdate) => {
  if (!props.buttonKey) return;
  
  try {
    const configKey = `printer_config_${props.buttonKey}`;
    let config = {};
    
    // 获取现有配置
    const existingConfigStr = localStorage.getItem(configKey);
    if (existingConfigStr) {
      config = JSON.parse(existingConfigStr);
    }
    
    // 更新配置
    const updatedConfig = { ...config, ...configUpdate };
    
    // 保存回本地存储
    localStorage.setItem(configKey, JSON.stringify(updatedConfig));
    
    console.log(`已为按钮 ${props.buttonKey} 保存配置:`, updatedConfig);
  } catch (error) {
    console.error('保存按钮打印机配置失败:', error);
  }
};

// 加载按钮特定的设置
const loadButtonSpecificSettings = () => {
  // 获取按钮特定的配置
  const buttonConfig = getPrinterConfigForButton();
  
  if (!buttonConfig) return;
  
  console.log(`加载按钮 ${props.buttonKey} 的缓存配置:`, buttonConfig);
  
  // 应用按钮特定配置
  if (buttonConfig.enabled !== undefined) {
    printServiceEnabled.value = buttonConfig.enabled;
  }
  
  if (buttonConfig.host) {
    portSettings.value.host = buttonConfig.host;
  }
  
  if (buttonConfig.port) {
    portSettings.value.port = buttonConfig.port;
  }
  
  // 注意：defaultPrinter在刷新打印机列表后设置
};

// 加载设置
const loadSettings = async () => {
  // 优先加载按钮特定的设置
  loadButtonSpecificSettings();
  
  // 如果没有按钮特定设置，则加载全局设置
  if (!props.buttonKey || !getPrinterConfigForButton()) {
    // 从localStorage获取打印服务启用状态
    const savedPrintServiceEnabled = localStorage.getItem('printServiceEnabled');
    if (savedPrintServiceEnabled !== null && printServiceEnabled.value === false) {
      printServiceEnabled.value = savedPrintServiceEnabled === 'true';
    }
    
    // 从本地存储获取保存的连接设置
    const savedHost = localStorage.getItem('printServiceHost');
    const savedPort = localStorage.getItem('printServicePort');
    
    if (savedHost && !portSettings.value.host) {
      portSettings.value.host = savedHost;
    }
    
    if (savedPort && !portSettings.value.port) {
      portSettings.value.port = parseInt(savedPort, 10) || 20000;
    }
  }
  
  // 只有在明确启用打印服务的情况下才初始化它
  if (printServiceEnabled.value) {
    console.log('打印服务已启用，正在初始化...');
    initPrintService()
  }
};

// 生命周期钩子
onMounted(() => {
  // 组件挂载时，如果弹窗已打开则初始化
  if (dialogVisible.value) {
    // loadSettings();
  }
});

onUnmounted(() => {
  // 组件卸载时清理资源，但不断开连接
  // 由主应用负责在适当的时候断开连接
  isInitialized.value = false;
});

// 暴露方法给父组件
defineExpose({
  refreshSettings: loadSettings,
  connectToCustomPort,
  refreshPrinterList,
  // 暴露新增的缓存方法
  getPrinterConfigForButton,
  savePrinterConfigForButton
});
</script>

<style scoped>
.printer-selector-container {
  padding: 10px;
}

.service-switch-container {
  display: flex;
  align-items: center;
  gap: 15px;
}

.connection-status-tag {
  margin-left: 10px;
}

.connection-settings {
  display: flex;
  align-items: center;
  gap: 10px;
}

.host-input {
  flex: 2;
}

.port-input {
  width: 120px;
}

.quick-input {
  flex: 1;
}

.info-icon {
  color: #909399;
  font-size: 16px;
  cursor: help;
}

.printer-select-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.printer-select {
  flex: 1;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
</style> 